const fs = require('fs');
const path = require('path');

function copy(source, target, cb) {
    console.log(source, target)
    const BUFFER_SIZE = 3;
    let r_offset = 0;
    let w_offset = 0;
    const buffer = Buffer.alloc(BUFFER_SIZE);

    fs.open(source, 'r', (err, rfd) => {
        fs.open(target, 'w', (err, wfd) => {
            function next() {
                fs.read(rfd, buffer, 0, BUFFER_SIZE, r_offset, (err, bytesRead) => {
                    if (err) cb(err)
                    if (bytesRead) {
                        fs.write(wfd, buffer, 0, BUFFER_SIZE, w_offset, (err, written) => {
                            r_offset += bytesRead
                            w_offset += written
                            next()
                        })
                    } else {
                        fs.close(rfd, () => { })
                        fs.close(wfd, () => { })
                        cb()
                    }
                })
            }
            next()
        })
    })
}

copy(path.resolve(__dirname, '01.test.js'), path.resolve(__dirname, '02.test.js'), (err) => {
    if (err) console.log(err)
    console.log('success')
})